package com.jdy.haoduoaiteacher.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;

import com.jdy.haoduoaiteacher.intface.IAsyncTask;
import com.jdy.haoduoaiteacher.util.CustomAsyncTask;
import com.jdy.haoduoaiteacher.util.HttpUtils;
import com.jdy.haoduoaiteacher.util.ResponseResult;
import com.jdy.haoduoaiteacher.util.StringInfoMatch;
import com.jdy.haoduoaiteacher.util.Tools;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

//import com.jdy.haoduoaiteacher.R;

@SuppressLint("HandlerLeak")
public class RegisterActivity extends BaseActivity {

  @InjectView(id = R.id.btn_next_step)
  private Button btn_next_step;
  @InjectView(id = R.id.get_captcha)
  private Button get_captcha;
  @InjectView(id = R.id.input_tel)
  private org.droidparts.widget.ClearableEditText input_tel;
  @InjectView(id = R.id.input_captcha)
  private org.droidparts.widget.ClearableEditText input_captcha;
  @InjectView(id = R.id.input_password)
  private org.droidparts.widget.ClearableEditText input_password;

  private Animation pressedAnimation;
  private boolean isInCountDown = false;
  private final StringInfoMatch stringMatch = new StringInfoMatch();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.register_layout);
    setTitle("注册");
    initView();
    showKeyboard();
  }

  private void updateBtnStatus() {
    if (Tools.isEmpty(input_tel.getText().toString())) {
      get_captcha.setEnabled(false);
    } else {
      if (!isInCountDown) {
        get_captcha.setEnabled(true);
      }
    }

    if (Tools.isEmpty(input_tel.getText().toString())
        || Tools.isEmpty(input_captcha.getText().toString())
        || Tools.isEmpty(input_password.getText().toString())
        || input_password.getText().toString().length() < 6) {
      btn_next_step.setEnabled(false);
    } else {
      btn_next_step.setEnabled(true);
    }
  }

  private void showKeyboard() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        InputMethodManager inputManager = (InputMethodManager) input_tel
            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(input_tel, 0);
      }
    }, 200);
  }

  private void addEditTextListener() {
    input_tel.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });

    input_captcha.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });

    input_password.addTextChangedListener(new TextWatcher() {
      @Override
      public void onTextChanged(CharSequence s, int start, int before, int count) {
      }

      @Override
      public void beforeTextChanged(CharSequence s, int start, int count,
          int after) {
      }

      @Override
      public void afterTextChanged(Editable s) {
        updateBtnStatus();
      }
    });
  }

  private void initView() {
    updateBtnStatus();
    addEditTextListener();

    pressedAnimation = AnimationUtils.loadAnimation(this, R.anim.anim_pressed);
    get_captcha.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (!stringMatch.ifMatchPhoneFormat(input_tel.getText().toString()
            .trim())) {
          toastShow("请输入正确的手机号码！");

          return;
        } else {
          v.startAnimation(pressedAnimation);
          pressedAnimation.setAnimationListener(new AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
              new CustomAsyncTask(RegisterActivity.this, new IAsyncTask() {

                @Override
                public void onRecieveData(Activity activity,
                    ResponseResult result) {
                  // if (Tools.isNotNullStr(result.data)) {
                  // toastShow(result.data);
                  // }
                  if (result.isSuccess()) {
                    startCountDown();
                  }
                }

                @Override
                public ResponseResult doInbackground(Activity activity) {

                  HashMap<String, Object> param_ = new HashMap<String, Object>();
                  param_.put(HttpUtils.TAG_MOBILE_I,
                      String.valueOf(input_tel.getText().toString()));
                  param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                  param_.put("type", 0);

                  return HttpUtils.startRequest(HttpUtils.HOST_API
                      + HttpUtils.GET_VERIY_CODE_METHOD_GET, param_,
                      HttpUtils.TAG_GET_REQUEST);

                }
              }).execute();
            }
          });
        }
      }
    });

    btn_next_step.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        if (Tools.isEmpty(input_tel.getText().toString())) {
          toastShow(getString(R.string.input_tel));
          return;
        }

        if (Tools.isEmpty(input_captcha.getText().toString())) {
          toastShow(getString(R.string.input_password));
          return;
        }

        if (Tools.isEmpty(input_password.getText().toString())) {
          toastShow(getString(R.string.input_password));
          return;
        }

        new CustomAsyncTask(RegisterActivity.this, new IAsyncTask() {

          @Override
          public void onRecieveData(Activity activity, ResponseResult result) {
            if (result.isSuccess()) {
              toastShow("成功");

              Intent intent = new Intent(RegisterActivity.this,
                  LoginActivity.class);
              intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
              startActivity(intent);

              overridePendingTransition(R.anim.push_left_in,
                  R.anim.push_left_out);
            } else {
              if (Tools.isNotNullStr(result.data)) {
                toastShow(result.data);
              }
            }
          }

          @Override
          public ResponseResult doInbackground(Activity activity) {

            HashMap<String, Object> param_ = new HashMap<String, Object>();

            param_.put(HttpUtils.TAG_MOBILE_I, input_tel.getText().toString());
            param_
                .put(HttpUtils.TAG_PWD_I, input_password.getText().toString());
            param_.put(HttpUtils.TAG_VERIFY_CODE_I, input_captcha.getText());
            param_.put(HttpUtils.TAG_PLATFORM_I, "android");
            param_.put(HttpUtils.TAG_TOKEN_I, "test");
            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

            return HttpUtils.startRequestEncrypt(HttpUtils.HOST_API
                + HttpUtils.REGISTER_METHOD_POST, param_,
                HttpUtils.TAG_POST_REQUEST);
          }
        }).execute();

      }
    });
  }

  private void startCountDown() {
    isInCountDown = true;
    get_captcha.setEnabled(false);
    new CountDownTimer(100000, 1000) {// CountDownTimer(edittext1.getText()+edittext2.getText())
                                      // also parse it to long

      @Override
      public void onTick(long millisUntilFinished) {
        get_captcha.setText(millisUntilFinished / 1000 + "秒后\n重取");
        // here you can have your logic to set text to edittext
      }

      @Override
      public void onFinish() {
        isInCountDown = false;
        get_captcha.setEnabled(true);
        get_captcha.setText(getString(R.string.get_captcha));
      }
    }.start();
  }
}